package org.turbobytes.unikey.generator;

import org.turbobytes.unikey.util.FileUtil;
import org.turbobytes.unikey.util.NumberUtil;
import static org.turbobytes.unikey.util.ConfigurationUtil.setConfigurationValue;
import org.turbobytes.unikey.util.exception.ConfigurationException;

import java.util.Random;
import java.util.Properties;

/**
 * A dummy implementation of <code>IdGenerator</code> to check the validity of various methods of the interface.
 * Can be used to generate random numbers, but it may not be useful in any production scenarios.
 *
 * @author Ganeshji Marwaha
 * @since Aug 5, 2010
 */
public class RandomIdGenerator extends BaseIdGenerator<Long> {
  public static final String DEFAULT_CONFIGURATION_FILE_NAME = "random_generator_default.properties";
  public static final String USER_CONFIGURATION_FILE_NAME = "random_generator.properties";
  public static final String MAX_VALUE = "maxValue";

  private Long maxValue;

  /**
   * Default constructor that configures itself using the default properties file bundled along with the library
   */
  public RandomIdGenerator() {
    this(FileUtil.loadPropertiesFromClasspath(USER_CONFIGURATION_FILE_NAME));
  }

  /**
   * Constructor which configures the instance by merging the default and user supplied configuration
   * @param userConfiguration - user supplied configuration
   */
  public RandomIdGenerator(Properties userConfiguration) {
    configure(userConfiguration);
  }

  /**
   * Generate an Id based on java's pseudo random number strategy
   * @return generated random id
   */
  public Long generate(String context) {
    Double randomDouble = new Random().nextDouble();
    randomDouble = randomDouble * this.maxValue;
    Long id = randomDouble.longValue();
    log.debug("Random Id: " + id);
    return id;
  }

  /**
   * Configures this instance of id generator by merging the default configuration with the user supplied
   * configuration.
   *
   * @param userConfiguration - user supplied configuration to override the default configuration
   */
  private void configure(Properties userConfiguration) {
    // This is the default configuration that is available within unikey jar
    Properties defaultConfiguration = FileUtil.loadPropertiesFromClasspath(DEFAULT_CONFIGURATION_FILE_NAME);

    // Override defaultConfiguration with userConfiguration. Will never return null
    Properties configuration = FileUtil.mergeProperties(defaultConfiguration, userConfiguration);

    setConfigurationValue(this, MAX_VALUE, configuration.getProperty(MAX_VALUE));
  }

  public Long getMaxValue() {
    return maxValue;
  }
}
